package com.hxd.qzg.module._admin.login;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.hxd.qzg.common.BaseController;
import com.hxd.qzg.common.Result;
import com.hxd.qzg.common.ServiceException;
import com.hxd.qzg.common.model.User;
import com.jfinal.plugin.activerecord.Page;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class UserController extends BaseController {

    private static final Log logger = LogFactory.get();

    /**
     * 显示登录界面
     */

	public void list() {

		String fromSql = "FROM  api_user WHERE 1=1";
		String key = get("key");

		if (StringUtils.isNotEmpty(key)) {
			fromSql = fromSql + " AND MATCH (username,real_name) AGAINST ('" + key + "')";

		}
		logger.info("sql>>>>>> {} ", fromSql);
		Page<User> page = User.dao.paginate(getInt("pageNum"), getInt("pageSize"), "select *", fromSql);
		renderJson(Result.success(page));
    }

	public void save() {

		String userName = get("userName");
		if (StringUtils.isEmpty(userName)) {
			throw new ServiceException("账户不能为空");

		}
		String password = get("password");
		if (StringUtils.isEmpty(password)) {
			throw new ServiceException("密码不能为空");

		}
		String realName = get("realName");
		if (StringUtils.isEmpty(realName)) {
			throw new ServiceException("realName不能为空");

		}
		User user = new User();
		user.setUsername(userName);
		user.setPwd(password);
		user.setRealName(realName);
		user.setLastDate(new Date());
		try {
			boolean bl = user.save();
			if (!bl) {
				throw new ServiceException("账号不符合规范");
			}
		} catch (Exception e) {

			throw new ServiceException("账号不符合规范");

		}
		renderJson(Result.success());
	}

	public void delete() {
		String id = get("id");

		if (StringUtils.isEmpty(id)) {
			throw new ServiceException("id不能为空");
		}
		Long delId = Long.valueOf(id);
		User user = new User();
		user.setId(delId);
		user.setIsDelete(1);
		user.update();
		renderJson(Result.success());
	}

	public void updatePwd() {
		String id = get("id");

		if (StringUtils.isEmpty(id)) {
			throw new ServiceException("id不能为空");
		}

		String pwd = get("pwd");

		if (StringUtils.isEmpty(pwd)) {
			throw new ServiceException("密码不能为空");
		}

		String realName = get("realName");

		if (StringUtils.isEmpty(realName)) {
			throw new ServiceException("真实姓名不能为空");
		}
		Long updateId = Long.valueOf(id);
		User user = new User();
		user.setId(updateId);
		user.setPwd(pwd);
		user.setRealName(realName);
		user.setLastDate(new Date());
		user.setUpdateTime(new Date());
		user.update();
		renderJson(Result.success());
	}
}
